package com.iweb.service;

import com.iweb.dao.UserDao;
import com.iweb.entity.User;
import com.iweb.role.UserType;
import com.iweb.utitls.MD5Util;

import java.sql.SQLException;

/**
 * @author ryl
 * @version 1.0
 * @data 2025/4/2 14:37
 */
public class UserService {
    private UserDao userDao;

    public UserService() throws Exception {
        this.userDao = new UserDao();
    }


    public boolean loginUser(String username, String password) {
        boolean loginStatus = false;
        // 首先尝试直接匹配未加密密码
        loginStatus = userDao.existsUsernameAndPassword(username, password);

        if (!loginStatus) {
            // 如果未加密密码验证失败，则尝试使用加密后的密码登录
            String encryptedPassword = MD5Util.encrypt(password);
            loginStatus = userDao.existsUsernameAndPassword(username, encryptedPassword);
        }
        return loginStatus;
    }

    /**
     * 判断用户是否存在
     * @param users
     */
    public boolean addUser(User users) throws SQLException {
        if (!userDao.existsUsername(users.getUsername())) {
            // 加密
            String encryptedPassword = MD5Util.encrypt(users.getPassword());
            users.setPassword(encryptedPassword);
            userDao.addUser(users);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除用户
     * @param username
     */
    public void deleteUser(String username) throws Exception {
        if (userDao.existsUsername(username)) {
            userDao.deleteUser(username);
        } else {
            System.out.println("该用户不存在...");
        }
    }

    /**
     * 更新密码
     * @param users
     */
    public void updateUser(User users) throws SQLException {
        if (userDao.existsUsername(users.getUsername())) {
            // 对密码加密
            String encryptedPassword = MD5Util.encrypt(users.getPassword());
            users.setPassword(encryptedPassword);
            userDao.updateUser(users);
        } else {
            System.out.println("该用户不存在...");
        }
    }

    public void selectAllUsers() {
        userDao.selectAllUsers();

    }

    public void selectUser(String username) {
        userDao.selectUser(username);
    }

    public void selectUsersPaged(int limit, int offset) {
        userDao.selectUsersPaged(limit, offset);

    }

    public UserType getUserType(String username) {
        return userDao.getUserType(username);
    }
}
